package com.fz.song.web.controller;


import com.fz.song.framework.common.R;
import com.fz.song.web.entity.User;
import com.fz.song.web.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "幂等性demo")
@Slf4j
@RestController
@RequestMapping("idempotent")
public class IdempotentController {

    @Autowired
    private IUserService userService;

    @ApiOperation(value = "查询操作", notes = "查询操作是天然的幂等操作,查询一次和查询多次效果是一样的")
    @GetMapping("gteUserById")
    public R login(Integer id) {
        User user = userService.getById(id);
        return R.ok("登录成功", user);
    }

    @ApiOperation(value = "删除操作", notes = "删除操作天然的幂等性,删除一次和删除多次效果是一样的")
    @DeleteMapping("removeById")
    public R removeById(Integer id) {
        userService.removeById(id);
        return R.ok("删除成功", true);
    }

    @ApiOperation(value = "新增数据", notes = "使用唯一索引防止新增脏数据,新增异常时候,使用唯一索引查询记录,查到后更新数据")
    @GetMapping("save")
    public R save(String name, String idCard) {
        User user = new User();
        user.setName(name);
        user.setIdCard(idCard);
        try {
            userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
            user = userService.getByIdCard(idCard);
            if (user != null) {
                user.setName(name);
                user.setIdCard(idCard);
                userService.updateById(user);
            }
        }
        return R.ok("新增数据", true);
    }


}
